﻿using System;
using System.Collections.Generic;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace TemplateLibraryConnector.ContentTypeListAddedEventReceiver
{
    /// <summary>
    /// List Events
    /// </summary>
    public class ContentTypeListAddedEventReceiver : SPListEventReceiver
    {
       /// <summary>
       /// A list was added.
       /// </summary>
       public override void ListAdded(SPListEventProperties properties)
       {
           base.ListAdded(properties);
           try
           {
               SPSecurity.RunWithElevatedPrivileges( delegate()
                {
                    var list = properties.Web.Lists[properties.ListId] as SPDocumentLibrary;

                    if (list != null && list.BaseTemplate == SPListTemplateType.DocumentLibrary && !list.IsSiteAssetsLibrary && !list.IsCatalog && !list.IsApplicationList)
                    {
                        var cTypes = Utility.ContentTypeAssociationJob.GetPublishedContentTypes(properties.Web.Site);

                        foreach (var ct in cTypes)
                        {
                            Utility.ContentTypeAssociationJob.AddContentTypeToList(ct, new List<SPDocumentLibrary>() { properties.Web.Lists[properties.ListId] as SPDocumentLibrary});
                        }
                        properties.InvalidateList();
                    }
                });
           }
           catch (Exception ex)
           {
               Utility.ULSLogger.LogError("An error occured for site" + properties.Web.Url, ex);
           }

       }


    }
}
